#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <cstdlib>

const double PI = 3.14159265358979323846;

void generate_data(int k, double h, bool zero_boundary) {
    // 生成连续数据
    int N_continuous = static_cast<int>(1.0 / 0.001);
    std::vector<double> x_continuous(N_continuous), y_continuous(N_continuous);
    for (int i = 0; i < N_continuous; ++i) {
        x_continuous[i] = i * 0.001;
        if (zero_boundary) {
            y_continuous[i] = sin(k * PI * x_continuous[i]);
        } else {
            y_continuous[i] = cos(k * PI * x_continuous[i]);
        }
    }

    std::ofstream file_continuous(zero_boundary ? "continuous_zero.dat" : "continuous_one.dat");
    for (int i = 0; i < N_continuous; ++i) {
        file_continuous << x_continuous[i] << " " << y_continuous[i] << std::endl;
    }
    file_continuous.close();

    // 生成离散数据
    int N_discrete = static_cast<int>(1.0 / h);
    std::vector<double> x_discrete(N_discrete), y_discrete(N_discrete);
    for (int i = 0; i < N_discrete; ++i) {
        x_discrete[i] = i * h;
        if (zero_boundary) {
            y_discrete[i] = sin(k * PI * x_discrete[i]);
        } else {
            y_discrete[i] = cos(k * PI * x_discrete[i]);
        }
    }

    std::ofstream file_discrete(zero_boundary ? "discrete_zero.dat" : "discrete_one.dat");
    for (int i = 0; i < N_discrete; ++i) {
        file_discrete << x_discrete[i] << " " << y_discrete[i] << std::endl;
    }
    file_discrete.close();
}

void plot_graph(int k, double h, bool zero_boundary) {
    std::string boundary_str = zero_boundary ? "zero" : "one";
    std::string continuous_file = zero_boundary ? "continuous_zero.dat" : "continuous_one.dat";
    std::string discrete_file = zero_boundary ? "discrete_zero.dat" : "discrete_one.dat";

    std::ofstream gnuplot_script("plot.gnuplot");
    gnuplot_script << "# Gnuplot 脚本\n"
                   << "set terminal pngcairo size 800,600 enhanced font 'Verdana,10'\n"
                   << "set output 'plot_k" << k << "_" << boundary_str << ".png'\n"
                   << "set title 'k = " << k << ", Boundary = " << boundary_str << "'\n"
                   << "set xlabel 'x'\n"
                   << "set ylabel 'y'\n"
                   << "set grid\n"
                   << "set yrange [-1.2:1.2]\n"
                   << "plot '" << continuous_file << "' using 1:2 with lines lt 1 lc rgb 'black' title 'Continuous', \\\n"
                   << "     '" << discrete_file << "' using 1:2 with linespoints pt 7 ps 1 lc rgb 'red' title 'Discrete'\n";
    gnuplot_script.close();

    std::system("gnuplot plot.gnuplot");
}

int main() {
    double h = 0.1; // 网格间距

    // 边界条件为0的情况
    for (int k : {10, 9, 11, 12}) {
        generate_data(k, h, true);
        plot_graph(k, h, true);
    }

    // 边界条件为1的情况
    for (int k : {10, 9, 11, 12}) {
        generate_data(k, h, false);
        plot_graph(k, h, false);
    }

    return 0;
}